
import { login, logout, wxLogin } from '@/utils/net'
import UserLogin from '../bean/UserLogin';
import ILoginModel from './ILoginModel';
import { useUserStore } from '@/stores/modules/user';
/**
 * Login数据持久化实现层
 */
export default class LoginModelImp implements ILoginModel {
    UserLogout(): Promise<void> {
        return new Promise((resolve, reject) => {
            logout().then(result => {
                if (result.data.status) {
                    useUserStore().setToken(undefined)
                    useUserStore().setSys(null)
                    useUserStore().setCurrentSystemName(undefined)
                    useUserStore().setCurrentSystemCode(undefined)
                    useUserStore().setUser(null)
                    uni.reLaunch({
                        url: '/pages/login/view/index'
                    });
                }
                resolve(result.data)
            }).catch((err) => {
                reject(new Error(err));
            })

        })
    }

    wxLogin(token: string): Promise<UserLogin> {
        return new Promise((resolve, reject) => {
            let userLogin = new UserLogin()
            wxLogin(token).then((result) => {
                if (result.data.status) {
                    uni.showToast({
                        title: '登录成功'
                    });
                    userLogin = result.data.data
                    useUserStore().setSys(userLogin.sys)
                    useUserStore().setUser(userLogin.user)
                    useUserStore().setToken(userLogin.sys.token)
                    uni.reLaunch({
                        url: "/pages/home/view/index"
                    });
                    resolve(userLogin)
                }
            }).catch((err) => {
                reject(new Error(err));
            })
        })
    }

    /**
     * @description: 用户登录
     * @param {string} yhdm
     * @param {string} yhmm
     * @return {*}
     */
    UserLogin(data: any, token?: string): Promise<UserLogin> {
        return new Promise((resolve, reject) => {
            let userLogin = new UserLogin()
            login(data, token).then((result) => {
                if (result.data.status) {
                    uni.showToast({
                        title: '登录成功'
                    });
                    userLogin = result.data.data
                    useUserStore().setSys(userLogin.sys)
                    useUserStore().setUser(userLogin.user)
                    useUserStore().setToken(userLogin.sys.token)
                    uni.reLaunch({
                        url: "/pages/home/view/index"
                    });
                    resolve(userLogin)
                }
            }).catch((err) => {
                reject(new Error(err));
            })
        })
    }
};
